package com.lottery.material.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Description：cookie工具类
 * Created by 朱正磊 on 2019-04-03 16:36
 */
public class CookieUtil {

    /**
     * description：设置cookie
     * user 朱正磊
     * time 2019-04-03 16:37
     * @param response 服务器响应对象
     * @param name cookie名称
     * @param value cookie值
     * @param maxAge cookie存活时间
     */
    public static void set(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * description：获取cookie
     * user 朱正磊
     * time 2019-04-03 16:38
     * @param request 客户端请求对象
     * @param name cookie名称
     * @return 返回cookie
     */
    public static Cookie get(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = readCookieMap(request);
        //如果存在则返回cookie，否则返回null
        return cookieMap.getOrDefault(name, null);
    }

    /**
     * description：将cookie封装成Map
     * user 朱正磊
     * time 2019-04-03 16:39
     * @param request 客户端请求对象
     * @return 返回cookie的Map集合
     */
    private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie: cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

}
